package cn.zh.blog.controller;

import cn.zh.blog.pojo.Blog;
import cn.zh.blog.service.BlogService;
import cn.zh.blog.service.TagService;
import cn.zh.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @Author 郑豪
 * @Date 2020/4/6 13:44
 **/
@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;
    @GetMapping("/index")
    public String index(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)Pageable pageable,
                        Model model){
        Page<Blog> page = blogService.listBlog(pageable);
        if (page.isEmpty()){
            model.addAttribute("message","没有博客文章");
        }
        model.addAttribute("page",page);
        model.addAttribute("types",typeService.listTypeTop(6));
        model.addAttribute("tags",tagService.listTagTop(12));
        model.addAttribute("recommendBlogs",blogService.listBlogTop(8));
        return "index";
    }


    @PostMapping("/search")
    public String search(@PageableDefault(size = 100,sort = {"updateTime"},direction = Sort.Direction.DESC)Pageable pageable,
                         Model model, @RequestParam String query){
        model.addAttribute("page",blogService.listBlog(pageable,"%" + query + "%"));
        model.addAttribute("query",query);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model) {
        model.addAttribute("blog",blogService.getAndConvert(id));
        return "blog";
    }

    @GetMapping("/error")
    public String error(){

        return "error/404";
    }

    @GetMapping("/about")
    public String about() {

        return "about";
    }

    @GetMapping("/footer/newblog")
    public String newBlogs(Model model) {
        model.addAttribute("newblogs",blogService.listBlogTop(4));
        return "_fragments :: newblogList";
    }

    @GetMapping("/")
    public String home(){

        return "home";
    }

}
